package com.example.chapter05;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Random;

public class LoginForgetActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_confirm;
    private String mVerifyCode, mPhone;
    private EditText et_password_first, et_password_second, et_verify_code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_forget);

        // 获取上一个页面传来的手机号码
        mPhone = getIntent().getStringExtra("phone");
        findViewById(R.id.btn_verify_code).setOnClickListener(this);
        btn_confirm = findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(this);
        // 获取两次密码输入框和验证码输入框
        et_password_first = findViewById(R.id.et_password_first);
        et_password_second = findViewById(R.id.et_password_second);
        et_verify_code = findViewById(R.id.et_verify_code);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_verify_code) {
            mVerifyCode = String.format("%06d", new Random().nextInt(999999));
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("请记住验证码");
            builder.setMessage("手机号码" + mPhone + "的验证码是:" + mVerifyCode);
            builder.setPositiveButton("我知道了", null);
            AlertDialog dialog = builder.create();
            dialog.show();
        } else if (v.getId() == R.id.btn_confirm) {
            String password_first = et_password_first.getText().toString();
            String password_second = et_password_second.getText().toString();
            if (password_first.length() < 6) {
                Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!password_first.equals(password_second)) {
                Toast.makeText(this, "两次密码不一致", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!mVerifyCode.equals(et_verify_code.getText().toString())) {
                Toast.makeText(this, "验证码错误", Toast.LENGTH_SHORT).show();
                return;
            }
            Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show();
            // 把修改好的密码传回上一个页面
            Intent intent = new Intent();
            intent.putExtra("new_password", password_first);
            setResult(RESULT_OK, intent);
            finish();
        }
    }
}